import { Message } from 'element-ui';
let publicKey = '3rsdf3RGSTE4TT3W'; // 测试值
let privateKey = 'f4tggft64643rsdf3RGSTE4TT3Wdrgeg4643rsdf3RGST3RGSTE4TT3Wdr'; // 测试值
let appId = '1000'; // 测试值

// 上传接口不加密
let uploadUrl = [
  '/lzc-gateway/user/v1/app/invite/import'
];
// 下载接口请求加密，响应文件流不加密
let downLoadUrl = [
  '/lzc-gateway/user/v1/app/invite/export'
];

import AresCrypto from ''; // 加密算法文件
import Base64 from 'js-base64/base64.js';
import store from '@/store';
import router from '@/router';
const vuexInit = () => {
  store.commit('userData/resetData');
};

import Axios from 'axios';
const axios = Axios.create({});
const cancelToken = Axios.CancelToken;
let source = cancelToken.source();

const headerFn = () => {
  let clientInfo = {
    'lzc-wb-devId': sessionStorage.getItem('deviceId'),
    'lzc-wb-devType': 'web',
    'lzc-wb-devChn': 'PC',
    'lzc-wb-devSys': 'web',
    'lzc-wb-devCorp': 'web'
  };
  let headerData = {
    'lzc-wb-token': store.getters.token || null,
    'lzc-wb-antiDup': null,
    'lzc-wb-cInfo': Base64.encode(JSON.stringify(clientInfo))
  };
  return headerData;
};
const isSecurity = (res) => {
  if (downLoadUrl.indexOf(res.config.url.split('?')[0]) === -1) {
    return true;
  } else {
    if (res.headers['content-type'].indexOf('applcation/json') === -1) {
      return false;
    } else {
      return true;
    }
  }
};

axios.interceptors.request.use(config => {
  config.cancelToken = source.token;
  config.headers = Object.assign(headerFn(), config.headers);
  if ((config.data && config.data.isThrow) || (config.params && config.params.isThrow)) {
    config.isThrow = true;
  }
  // 是否加密
  if (!window.configVUE.notSecurity && uploadUrl.indexOf(config.url) === -1) {
    let encryptKey = AresCrypto.generateKey();
    config.encryptKey = encryptKey;
    if (config.method === 'get') {
      let _v = AresCrypto.encryptKey4Get(appId, publicKey, privateKey, config.encryptKey);
      if (config.url.indexOf('?') === -1) {
        config.url = config.url + '?' + _v;
      } else {
        config.url = config.url + '&' + _v;
      }
    } else {
      config.data = {
        body: AresCrypto.encrypt(publicKey, privateKey, config.encryptKey, JSON.stringify(config.data || {}))
      };
    }
  }
  return config;
}, err => {
  return Promise.reject(err);
});

axios.interceptors.response.use(res => {
  let body = {};
  if (res.data && res.data.head) {
    // 走网关
    body = res.data.body;
  } else {
    body = res.data;
  }
  // 判断是否解密
  let downIsSecurity = isSecurity(res);
  if (!window.configVUE.notSecurity && res.config.encryptKey && downIsSecurity) {
    // 判断对象是不是blob类型
    if (res.data instanceof Blob && res.data.type === 'application/json') {
      try {
        return res.data.text().then(txt => {
          let rsp = JSON.parse(txt);
          body = JSON.parse(AresCrypto.decrypt(res.config.encryptKey, rsp.body));
          return Promise.resolve(body);
        }).catch(r => {
          return Promise.reject(r);
        });
      } catch (err) {
        return Promise.reject(err);
      }
    } else {
      // 如果网关报错，抛出错误
      if (res.data.head && res.data.head.H_STATUS !== '000000') {
        source.cancel();
        Message.alert(res.data.head.H_MSG, '系统提示', {
          confirmButtonText: '确定',
          type: 'warning',
          showClose: false,
          callback: () => {
            source = cancelToken.source();
          }
        });
        return Promise.reject({});
      }
      body = JSON.parse(AresCrypto.decrypt(res.config.encryptKey, body));
    }
  }
  if (['UR0002', 'UR0009', 'UR1018'].includes(body.errorCode)) {
    source.cancel();
    let text = {
      UR0002: '会话超时，请重新登录',
      UR0009: '用户已在其它设备登录，请注意账号安全',
      UR1018: '企业已注销，请重新登录'
    };
    Message.alert(text[body.errorCode], '系统提示', {
      confirmButtonText: '确定',
      type: 'warning',
      showClose: false,
      callback: () => {
        source = cancelToken.source();
        sessionStorage.clear();
        vuexInit();
        router.replace({
          path: '/login'
        });
      }
    });
  }
  if (res.config && res.config.isThrow) {
    body.webIsThrow = true;
  }
  return Promise.resolve(body);
}, err => {
  const status = (err.response && err.response.status) || '';
  const data = (err.response && err.response.data) || '';
  if (data.message) {
    return Promise.reject(data.message);
  }
  if (err.code === 'ECONNABORTED' && err.message.indexOf('timeout') != -1) {
    return Promise.reject('请求超时...');
  }
  switch (status) {
    case 401:
      return Promise.reject(data);
    case 403:
      return Promise.reject(data);
    case 404:
      return Promise.reject(data);
    case 500:
      return Promise.reject(data);
    default:
      break;
  }
  let responseStr = err.response.data.body;
  if (!window.configVUE.notSecurity) {
    if (err.response.data) {
      try {
        responseStr = JSON.parse(AresCrypto.decrypt(err.config.encryptKey, responseStr));
      } catch (err) {
      }
    }
  }
  return Promise.reject(responseStr);
});

export default axios;
